<template>
  <div
    style="width: 100%; display: inline-flex; justify-content: space-between; align-items: center"
  >
    <el-tabs
      v-model="activeTab"
      class="demo-tabs"
      style="padding-left: 10px"
      @tab-click="handleAticeTabClick"
    >
      <el-tab-pane label="回复" name="0"></el-tab-pane>
      <el-tab-pane label="内部回复" name="1" v-if="isOtherConver"></el-tab-pane>
      <el-tab-pane label="匿名回复" name="2" v-if="isOtherConver && isniming"></el-tab-pane>
    </el-tabs>
    <div class="toolbar" v-show="activeTab == '0'">
      <!-- 表情包 -->
      <span :title="$t('chat.emoji')" class="emoticon" @click="sendEmojiClick">
        <svg-icon iconClass="iconxiaolian" class="icon-hover" />
      </span>
      <!-- 发送表单 -->
      <!-- <el-icon
        class="icon-hover"
        style="
          width: 42px;
          align-items: center;
          justify-content: center;
          display: flex;
          height: 40px;
          padding: 4px;
          position: relative;
          text-align: center;
          color: #808080;
        "
        @click="visible = true"
        ><Postcard
      /></el-icon> -->
      <!-- 用户信息 -->

      <!-- 图片 -->
      <span v-show="!isRobot(toAccount)" :title="$t('chat.picture')" @click="sendImageClick">
        <svg-icon iconClass="icontupian" class="icon-hover" />
      </span>
      <!-- 文件 -->
      <span v-show="!isRobot(toAccount)" :title="$t('chat.file')" @click="sendFileClick">
        <svg-icon iconClass="iconwenjianjia" class="icon-hover" />
      </span>
      <!-- 截图 -->
      <!-- <span v-show="!isRobot(toAccount)" :title="$t('chat.screenshot')" @click="clickCscreenshot">
        <svg-icon iconClass="iconjietu" class="icon-hover" />
      </span> -->
      <!-- 五星好评 -->
      <!-- <span title="评价邀请" @click="handleReview">
        <el-icon class="icon-hover"><Star /></el-icon>
      </span> -->
      <!-- 机器人配置 -->
      <span title="机器人托管" @click="handleRobotBox">
        <svg-icon
          iconClass="robot"
          class="icon-hover robot"
          :style="trusteeshipValue ? 'color: blue' : ''"
        />
      </span>
      <!-- 窗口抖动 -->
      <span
        v-show="currentType === 'C2C' && isElectron"
        :title="$t('chat.windowJitter')"
        @click="onShake"
      >
        <el-icon class="icon-hover"><Iphone /></el-icon>
      </span>
      <!-- 自定义消息 -->
      <span @click="customMessage" v-if="false">
        <el-icon class="icon-hover"><Sunny /></el-icon>
      </span>
      <!-- 滚动到底部 -->
      <span
        :title="$t('chat.scrollToTheBottom')"
        class="chat_vot"
        @click="onTobBottom"
        v-show="tobottom"
      >
        <el-icon class="svg-left icon-hover">
          <DArrowLeft />
        </el-icon>
      </span>
      <!-- <span
      :title="fullScreen ? $t('chat.recover') : $t('chat.launch')"
      class="style-enlarge"
      @click="onEnlarge(fullScreen)"
    >
      <svg-icon v-if="fullScreen" iconClass="narrow" class="icon-hover" />
      <svg-icon v-else iconClass="enlarge" class="icon-hover" />
    </span> -->
      <input
        type="file"
        ref="imagePicker"
        accept=".jpg, .jpeg, .png, .gif, .bmp"
        @change="sendImage"
        hidden
      />
      <input type="file" ref="filePicker" @change="sendFile" hidden />
      <!-- <input
      type="file"
      ref="videoPicker"
      @change="sendVideo"
      accept=".mp4"
      hidden
    /> -->

      <!-- <RobotOptions v-if="isRobot(toAccount)" /> -->
      <EmotionPackBox @setEmoji="setEmoji" ref="emjRef" />
    </div>

    <el-dialog title="发送表单" v-model="visible" width="40%">
      <el-checkbox-group v-model="checkList" @change="handleChecklist">
        <el-checkbox
          :label="item.label"
          :value="item.value"
          v-for="(item, index) in customerInfoModle"
          :key="index"
        />
      </el-checkbox-group>
      <template #footer>
        <span>
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="sendCustomerInfo">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { createCustomMsg } from "@/api/im-sdk-api/index";
import { isRobot, screenshot } from "@/utils/chat/index";
import { isElectron } from "@/utils/common";
import { useGetters, useState } from "@/utils/hooks/useMapper";
import emitter from "@/utils/mitt-bus";
import { ref, computed, watchEffect } from "vue";
import { useStore } from "vuex";
import EmotionPackBox from "./EmotionPackBox.vue";
import RobotOptions from "./RobotOptions.vue";
import dayjs from "dayjs";
import { successMessage, warnMessage, errorMessage } from "@/utils/message";
import { trusteeship, SendGroupSystemNotification } from "@/api/node-admin-api/chat.js";
import { getKefuInfo } from "@/api/node-admin-api/role.js";
const emojiQq = require("@/utils/emoji/emoji-map-qq");
const emojiDouyin = require("@/utils/emoji/emoji-map-douyin");
import storage from "@/utils/localforage/index";
import { USER_MODEL } from "@/constants/index";

const emjRef = ref();
const tobottom = ref();
const imagePicker = ref();
const filePicker = ref();
const checkList = ref([]);
const { commit, dispatch } = useStore();
const customerInfoModle = ref([
  { label: "姓名", value: "name" },
  { label: "电话", value: "phone" },
  { label: "年龄", value: "age" },
  { label: "性别", value: "sex" },
  { label: "QQ", value: "QQ" },
  { label: "微信", value: "wechat" },
  { label: "地址", value: "address" },
  { label: "邮箱", value: "email" },
  { label: "联系人", value: "contact" },
  { label: "备注", value: "remark" },
]);
const props = defineProps({
  detailItem: Object,
  isniming: Boolean,
});
const activeTab = ref("0"); // 0-回复，1-内部回复，2-匿名回复

const emit = defineEmits([
  "setToolbar",
  "sendCustomerInfo",
  "handleToolbarAticeTabClick",
  "handleTrusteeshipValueChange",
]);
const { toAccount, currentType } = useGetters(["toAccount", "currentType"]);
const { fullScreen, currentConversation } = useState({
  fullScreen: (state) => state.settings.fullScreen,
  currentConversation: (state) => state.conversation.currentConversation,
});

const userInfo = ref(null);
watchEffect(async () => {
  userInfo.value = await storage.get(USER_MODEL);
});

const isOtherConver = computed(() => (label) => {
  if (!userInfo.value || !props.detailItem.value) return false;
  return props.detailItem.value.handler !== userInfo.value.user.userId;
});

const handleAticeTabClick = ({ props }, event) => {
  const { label, name } = props;
  emit("handleToolbarAticeTabClick", name);
};

const handleTrusteeshipValueChange = () => {
  emit("handleTrusteeshipValueChange", trusteeshipValue.value);
};

const sendEmojiClick = () => {
  emjRef.value.setFlag(true);
};
const handleChecklist = (val) => {
  const list = [...checkList.value];
  const value = val.target._value;
  const index = list.findIndex((item) => item === value);

  if (index !== -1) {
    list.splice(index, 1);
  } else {
    list.push(value);
  }
  checkList.value = list;
  console.log(checkList.value);
};
const visible = ref(false);
const sendCustomerInfo = () => {
  getKefu();
};

// 获取看客服的昵称
const getKefu = () => {
  // loading.value = true;
  const userInfo = storage.get(USER_MODEL);
  getKefuInfo({ userid: userInfo.user.userId })
    .then((res) => {
      if (res.code == 20000) {
        let message = [];
        customerInfoModle.value.map((item) => {
          if (checkList.value.includes(item.value)) {
            message.push(item.label);
          }
        });
        const time = dayjs(new Date()).format("YYYY/MM/DD HH:mm:ss");
        const content = `${time} ${res.data.result.nickname}发送${message.join("、")}`;
        sendSystemMsg({ content: content });
      }
    })
    .catch((res) => {
      errorMessage(res.message);
    })
    .finally((res) => {
      visible.value = false;
      // loading.value = false;
    });
};

const sendSystemMsg = (temp) => {
  const sessionId = currentConversation.value.conversationID.replace("GROUP", "");
  const params = {
    ...temp,
    groupId: sessionId,
  };
  SendGroupSystemNotification(params).then((res) => {
    if (res.code == 20000) {
      visible.value = false;
    }
  });
};

// 评价 =》》 04/17 14:30:51 1号在线客服主动发起评价
const handleReview = () => {
  const time = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
};
const trusteeshipValue = ref(false);
// 开启机器人托管
function handleRobotBox() {
  if (!currentConversation.value.conversationID) return;
  trusteeshipValue.value = !trusteeshipValue.value;
  let sessionId = currentConversation.value.conversationID;
  const params = {
    sessionId: Number(sessionId.replace("GROUP", "")),
    trusteeship: trusteeshipValue.value,
  };
  trusteeship(params)
    .then((res) => {
      if (res.code == 20000) {
        successMessage(`机器人${trusteeshipValue.value ? "托管成功" : "取消托管成功"}`);
      }
    })
    .catch((e) => {
      errorMessage("更改机器人托管状态失败");
    });
}
function openRobotBox() {
  emitter.emit("onRobotBox", true);
}
const setEmoji = (item, table) => {
  let url = "";
  if (table == "QQ") {
    url = require("@/assets/emoji/" + emojiQq.emojiMap[item]);
  } else {
    url = require("@/assets/emoji/" + emojiDouyin.emojiMap[item]);
  }
  emit("setToolbar", { data: { url, item }, key: "setEmoj" });
};
const sendImageClick = () => {
  let $el = imagePicker.value;
  $el.value = null;
  $el.click();
};
const sendFileClick = () => {
  let $el = filePicker.value;
  $el.value = null;
  $el.click();
};
// 截图
const clickCscreenshot = () => {
  commit("ipcRenderer", { key: "screenshot" });
};
let lastExecutionTimestamp = 0;
const onShake = () => {
  let startTime = Date.now();
  if (startTime - lastExecutionTimestamp < 5000) {
    // 在 5 秒内已经执行过一次，不再执行
    commit("showMessage", {
      message: "发送窗口抖动太过频繁,请稍后再试!",
      type: "warning",
    });
    return;
  }
  // 更新上次执行时间戳
  lastExecutionTimestamp = startTime;
  commit("ipcRenderer", { key: "shakeWindow" });
  const message = createCustomMsg({
    convId: toAccount.value,
    convType: currentType.value,
    customType: "dithering",
  });
  dispatch("SESSION_MESSAGE_SENDING", {
    payload: { convId: currentConversation.value.conversationID, message },
  });
};
const onEnlarge = (value) => {
  commit("UPDATE_USER_SETUP", { key: "fullScreen", value: !value });
};

function customMessage() {
  const message = createCustomMsg({
    convId: toAccount.value,
    convType: currentType.value,
    customType: "loading",
  });
  dispatch("SESSION_MESSAGE_SENDING", {
    payload: {
      convId: currentConversation.value.conversationID,
      message,
    },
  });
}

function sendImage(e) {
  emit("setToolbar", {
    key: "setPicture",
    data: { files: e.target.files[0] },
  });
}
function sendFile(e) {
  emit("setToolbar", {
    key: "setParsefile",
    data: { files: e.target.files[0] },
  });
}
const onTobBottom = () => {
  emitter.emit("updataScroll");
};
emitter.on("onisbot", (state) => {
  tobottom.value = !state;
});
// defineExpose({ handleToolbarAticeTabClick });
</script>
<style lang="scss" scoped>
.toolbar {
  height: 40px;
  padding: 0 5px;
  display: flex;
  position: relative;
  background: var(--color-toolbar);
  & > span {
    width: 42px;
    align-items: center;
    justify-content: center;
    display: flex;
    height: 40px;
    padding: 4px;
    position: relative;
    text-align: center;
    color: #808080;
  }
  .robot {
    stroke: unset;
    cursor: pointer;
  }
  & > .icon:hover:after {
    font-size: 13px;
    display: inline-block;
    content: attr(data-title);
    text-align: center;
    color: rgba(0, 0, 0, 0.75);
    position: absolute;
    left: 17px;
    top: 38px;
    border-radius: 3px;
    // border: 1px solid #e9e9e9;
    background-color: #eaeaea;
    white-space: nowrap;
    padding: 2px 5px;
    z-index: 9999;
  }
}
.chat_vot {
  cursor: pointer;
  animation: chat_top 0.3s ease;
  .svg-left {
    transform: rotate(-90deg);
  }
}
.style-enlarge {
  margin-left: auto;
}

@keyframes chat_top {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
